package com.argticling.dao.impl;

import com.argticling.dao.impl.hibernate.HibernateUtil;
import com.argticling.model.TextArticleFragment;

import java.util.List;

public class TextFragmentDAOImplementacion extends AbstractDAOImplementation {

    public void commitModifiedTextFragments(List<TextArticleFragment> textFragments, String id) {
        for (TextArticleFragment textFrag : textFragments) {
            TextArticleFragment oldTextFrag = getTextFragmentById(textFrag.getId());
            if (textFrag.hashCode() == (oldTextFrag.hashCode())) {
                new HibernateUtil().persist(textFrag);
            }
        }
    }

    public void commitAllTextFragments(List<TextArticleFragment> textFragments, String id) {
        for (TextArticleFragment textFrag : textFragments) {
            textFrag.setArticleID(id);
            new HibernateUtil().persist(textFrag);
        }
    }

    public List<TextArticleFragment> getImageFragmentsByArticleId(String id) {
        List<TextArticleFragment> textFrag = new HibernateUtil().getSession().createQuery("FROM TextArticleFragment as textFrag where " +
                "textFrag.articleID = ?").setString(0, id).list();
        return textFrag;
    }

    public TextArticleFragment getTextFragmentById(String id) {
        TextArticleFragment textFrag = (TextArticleFragment) new HibernateUtil().getSession().createQuery("FROM TextArticleFragment as textFrag where " +
                "textFrag.id = ?").setString(0, id).uniqueResult();
        return textFrag;
    }
}
